package com.jymf.system.service;

import com.jymf.common.CommonUtils;
import com.jymf.common.ConfigValue;
import com.jymf.common.MD5;
import com.jymf.common.TreeUtil;
import com.jymf.model.*;
import com.jymf.model.Dictionary;
import com.jymf.system.dao.CommSystemDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author zyj
 * @create 2017-06-06
 **/
@Service
public class CommSystemService {
    Logger logger = LoggerFactory.getLogger(CommSystemService.class);

    @Autowired
    private CommSystemDao commSystemDao;

    /**
     * 数据
     * @return
     */
    public List<TreeVo> getChildrenTree(String id){
        List<TreeVo> treeVos = new ArrayList<TreeVo>();
        List<Resource> resourceList = null ;
        List<Resource> childrenRe = new ArrayList<Resource>();
        try {
            resourceList = commSystemDao.getResourceByParentId(null);
            Iterator<Resource> iterator = resourceList.iterator();
            while (iterator.hasNext()){//查找id对应子节点
                Resource resource = iterator.next();
                Integer parentId = resource.getParentId();
                if(parentId!=null&&parentId==Integer.parseInt(id)){
                    childrenRe.add(resource);
                }
            }

          //转TreeVo
          treeVos = coverTree(childrenRe, resourceList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  treeVos;
    }

    /**
     * 获取字典
     * @param id
     * @return
     */
    public List<TreeVo> getdictTree(){

        List<TreeVo> treeVoList = new ArrayList<TreeVo>();
        try {
            List<Dictionary> listValue = commSystemDao.selectDict(new HashMap<String, Object>());
            Iterator<Dictionary> iterator = listValue.iterator();
            while (iterator.hasNext()){
                Dictionary dictionary = iterator.next();
                TreeVo treeVo1 = new TreeVo();
                treeVo1.setId(dictionary.getDictValue());
                treeVo1.setName(dictionary.getDictName());
                treeVo1.setIsParent(false);
                treeVo1.setParentId("1");
                treeVoList.add(treeVo1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return  treeVoList;
    }

    /**
     * 转换成树结构
     * @param resourceList 需要转换的list
     * @param resourceList1 所有资源
     * @return
     */
    public List<TreeVo> coverTree(List<Resource> resourceList,List<Resource> resourceList1){
        List<TreeVo> listTree = new ArrayList<TreeVo>();
        if(resourceList!=null&&resourceList.size()>0){
            Iterator<Resource> iterator = resourceList.iterator();
            while (iterator.hasNext()){
                Resource next = iterator.next();
                int id = next.getId();
                TreeVo treeVo = new TreeVo();
                treeVo.setId(String.valueOf(id));
                treeVo.setName(next.getName());
                //判断是否为父级
                boolean b = false;
                Iterator<Resource> iterator1 = resourceList1.iterator();
                while (iterator1.hasNext()){
                    Resource next1 = iterator1.next();
                    if (next1.getParentId()==id){
                        b = true;
                    }
                }

                treeVo.setIsParent(b);
                listTree.add(treeVo);
            }
        }

        return  listTree;
    }

    /**
     * 保存节点
     * @param map
     * @return
     */
    public boolean saveNode(Map<String,Object> map){
        boolean b = false;
        try {
            commSystemDao.saveNode(map);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 获取资源列表
     * @param id
     * @return
     */
    public Resource getResourceById(int id){
        Resource resource = new Resource();
        try {
            resource = commSystemDao.getResourceById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return  resource;
    }

    /**
     * 修改节点
     * @param map
     * @return
     */
    public boolean editNode(Map<String,Object> map){
        boolean b = false;
        try {
            commSystemDao.editNode(map);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 删除节点
     * @return
     */
    public boolean deleteNode(int id){
        boolean b = false;
        try {
            commSystemDao.deleteNode(id);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 获取角色列表
     * @param map
     * @return
     */
    public Map<String, Object> getRolePage(Map<String, Object> map){
        Map<String, Object> maps = new HashMap<String, Object>();
        List<Role> lists = new ArrayList<Role>();
        int total = 0;
        try {
            lists = commSystemDao.getRolesList(map);//数据
            total = commSystemDao.getTotal(map);
            maps.put("info", lists);
            maps.put("total", total);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return maps;
    }

    public List<Role> getRolePageInfo(Page page){
        return  commSystemDao.getRolesPageList(page);
    }

    public List<Users> getUserPageList(Page page){
        return  commSystemDao.getUserPageList(page);
    }

    /**
     * 获取用户列表
     * @param map
     * @return
     */
    public Map<String, Object> getUserPage(Map<String, Object> map){
        Map<String, Object> maps = new HashMap<String, Object>();
        List<Users> lists = new ArrayList<Users>();
        int total = 0;
        try {
            lists = commSystemDao.getUserList(map);//数据
            total = commSystemDao.getUserTotal(map);
            maps.put("info", lists);
            maps.put("total", total);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return maps;
    }

    /**
     * 保存角色
     * @param map
     */
    public boolean saveRole(Map<String,Object> map){
        boolean b = false;
        try {
            commSystemDao.saveRole(map);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 修改角色
     * @param map
     * @return
     */
    public boolean editRole(Map<String,Object> map){
        boolean b = false;
        try {
            commSystemDao.editRole(map);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 获取资源树
     * @return
     */
    public List<TreeVo> getResource(String logName){
        List<TreeVo> listTrees = null;
        try {
            List<Resource> resourceList = commSystemDao.getResourceByParentId(null);
            listTrees = TreeUtil.convertTreeVo(CommonUtils.coverTree(resourceList,logName), "1");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return listTrees;
    }

    /**
     * 修改角色权限
     * @param map
     * @return
     */
    @Transactional(readOnly = false)
    public void editRoleResource(Map<String, Object> map) throws Exception{
//        SqlSession session = sessionFactory.openSession(false);
//        CommSystemDao daos = session.getMapper(CommSystemDao.class);
            //step1:先删除角色资源
            commSystemDao.deleteRoleRes(Integer.parseInt(String.valueOf(map.get("roleid"))));

            //step2：新增角色资源
            Object roleid = map.get("roleid");
            String[] resIds = map.get("sourceid").toString().split(",");
            List<Map<String, Object>> listRes = new ArrayList<Map<String, Object>>();
            for(int i=0;i<resIds.length;i++){
                if(resIds[i]!=null&&!"".equals(resIds[i])){
                    Map<String, Object> maps = new HashMap<String, Object>();
                    maps.put("roleid", roleid);
                    maps.put("sourceid", resIds[i]);
                    listRes.add(maps);
                }
            }
            commSystemDao.addRoleRes(listRes);

    }

    /**
     * 获取资源列表
     * @param roleID
     * @return
     */
    public List<Rolesource> getRoleSource(String roleID){
        List<Rolesource> list = new ArrayList<Rolesource>();
        try {
            list = commSystemDao.getRoleRes(Integer.parseInt(roleID));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    @Transactional(readOnly = false)
    public void  deleteRole(String roleID) throws Exception{
        //step1:先删除角色资源
        commSystemDao.deleteRoleRes(Integer.parseInt(roleID));

        //step2：删除角色
        commSystemDao.deleteRole(Integer.parseInt(roleID));


    }

    /**
     * 保存用户
     * @param map
     * @return
     */
    public boolean saveUsers(Map<String,Object> map){
        boolean b = false;
        try {
            commSystemDao.saveUsers(map);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 修改用户
     * @param map
     * @return
     */
    public boolean editUsers(Map<String,Object> map){
        boolean b = false;
        try {
            commSystemDao.editUsers(map);
            b = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return b;
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    public Users getUserInfo(String id){
        Users userInfo= null;
        try {
            userInfo = commSystemDao.getUserById(Integer.parseInt(id));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userInfo;
    }

    /**
     * 获取角色
     * @return
     */
    public List<Map<String, Object>> getUserRolesList(String lgName){
        List<Map<String, Object>> list = null;
        try {
            list = commSystemDao.getUserRolesList(lgName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 获取用户角色
     * @return
     */
    public List<Integer> getUserRoleInfo(String id){
        List<Integer> list = null;
        try {
            list = commSystemDao.getUserRoleInfo(Integer.parseInt(id));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 修改用户
     * @param map
     * @return
     */
    @Transactional(readOnly = false)
    public void editUserRoles(Map<String, Object> map)throws Exception{
            //step1:先删除角色资源
            commSystemDao.deleteUserRole(Integer.parseInt(String.valueOf(map.get("userId"))));

            //step2：新增角色资源
            Object userId = map.get("userId");
            String[] resIds = map.get("roleIds").toString().split(",");
            List<Map<String, Object>> listRes = new ArrayList<Map<String, Object>>();
            for(int i=0;i<resIds.length;i++){
                if(resIds[i]!=null&&!"".equals(resIds[i])){
                    Map<String, Object> maps = new HashMap<String, Object>();
                    maps.put("userId", userId);
                    maps.put("roleId", resIds[i]);
                    listRes.add(maps);
                }
            }
            if(listRes!=null&&listRes.size()>0){
                commSystemDao.addUserRole(listRes);
            }

    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Transactional(readOnly = false)
    public void deleteUsers(String userId)throws Exception{
        //step1:先删除角色资源
        commSystemDao.deleteUserRole(Integer.parseInt(userId));
        //step2：删除角色
        commSystemDao.deleteUser(Integer.parseInt(userId));
    }

    /**
     * 重置密码
     * @param id
     */
    public void editPasswd(String id)throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("passwd", MD5.EncoderPwdByMd5(ConfigValue.getValue("lgPasswd")));
        map.put("id", id);
        commSystemDao.editPasswd(map);
    }

    /**
     * 获取字典类型
     * @param page
     * @return
     */
    public List<Map<String, Object>> getDictList(Page<Map<String, Object>> page){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        try {
            list = commSystemDao.queryDict(page);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }

        return  list;
    }

    /**
     * 获取字典
     * @param page
     * @return
     */
    public List<Map<String, Object>> getDictDataList(Page<Map<String, Object>> page){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        try {
            list = commSystemDao.queryDictData(page);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }

        return  list;
    }

    //保存字典类型
    public void insertDictionary(Dictionary dictionary) throws Exception{
        commSystemDao.insertDictionary(dictionary);
    }

    //保存字典数据
    public void inserDictionaryData(Dictionarydata dictionarydata) throws Exception{
        commSystemDao.insertDictionaryData(dictionarydata);
    }

    public Dictionarydata getDictDataById(int id){
        Dictionarydata dictionarydata = new Dictionarydata();
        try {
             dictionarydata = commSystemDao.queryDictDataById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dictionarydata;
    }

    public void updateDictData(Dictionarydata dictionarydata) throws Exception{
        commSystemDao.updateDictionaryData(dictionarydata);
    }

    public List<Dictionarydata> queryDataByDict(String dictData){
        List<Dictionarydata> listValue = new ArrayList<Dictionarydata>();
        try {
            listValue = commSystemDao.queryDataByDict(dictData);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return listValue;
    }

}
